package com.zimi.core.security;

import com.zimi.core.bean.AuthUser;
import com.zimi.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Collections;

import static com.zimi.core.security.AuthenticationFilter.isAppRequest;

@Component
@Slf4j
public class Authent implements AuthenticationProvider {

    private final AuthUserService authUserService;

    @Autowired
    public Authent(AuthUserService authUserService) {
        this.authUserService = authUserService;
    }

    @Override
    public Authentication authenticate(Authentication auth)
            throws AuthenticationException {
        if (isAppRequest) return new UsernamePasswordAuthenticationToken
                (null, null, Collections.emptyList());
        String username = auth.getName();
        String password = MD5Util.encode(auth.getCredentials()
                .toString());
        AuthUser user = authUserService.loadUserByUsername(username);
        if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken
                    (username, password, Collections.emptyList());
        } else {
            throw new BadCredentialsException("External system authentication failed");
        }
    }

    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
}